/*
#Copyright (c) 2013, Philippe Bordron <philippe.bordron@gmail.com>
#
# This file is part of SIPPER.
#
# DCC is free software: you can redistribute it and/or modify
# it under the terms of the GNU LESSER GENERAL PUBLIC LICENSE as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DCC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU LESSER GENERAL PUBLIC LICENSE for more details.
#
# You should have received a copy of the GNU LESSER GENERAL PUBLIC LICENSE
# along with SIPPER.  If not, see <http://www.gnu.org/licenses/>
*/
package combi.sipper.io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IOAssociation {
	
	///TODO need to use generics
	
	public static Map<String, Set<String>> loadString(String fileIn, String tag) throws IOException
	{
		Map<String, Set<String>> result = new HashMap<String, Set<String>>();
		BufferedReader in = new BufferedReader (new FileReader (fileIn));
		Matcher m;
		Matcher m2;
		String nonEmpty = "(?:(\\S+))";
		Pattern reco = Pattern.compile(tag);
		Pattern recoNb = Pattern.compile(nonEmpty);
		String ch;
		while ((ch = in.readLine()) != null)
		{
			try
			{
				m = reco.matcher(ch);
				while (m.find())
				{
					Set<String> set = result.get(m.group(1));
					if (set == null)
					{
						set = new HashSet<String>();
						result.put(m.group(1), set);
					}
					m2 = recoNb.matcher(m.group(2));
					while (m2.find())
					{
						set.add(m2.group(1));
					}
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		in.close();
		return result;
	}
	
	//Same as above but with Integer
	public static Map<String, Set<Integer>> loadInteger(String fileIn, String tag) throws IOException
	{
		Map<String, Set<Integer>> result = new HashMap<String, Set<Integer>>();
		BufferedReader in = new BufferedReader (new FileReader (fileIn));
		Matcher m;
		Matcher m2;
		String nb = "(?:([0-9]+))";
		Pattern reco = Pattern.compile(tag);
		Pattern recoNb = Pattern.compile(nb);
		String ch;
		while ((ch = in.readLine()) != null)
		{
			try
			{
				m = reco.matcher(ch);
				while (m.find())
				{
					Set<Integer> set = result.get(m.group(1));
					if (set == null)
					{
						set = new HashSet<Integer>();
						result.put(m.group(1), set);
					}
					m2 = recoNb.matcher(m.group(2));
					while (m2.find())
					{
						set.add(Integer.valueOf(m2.group(1)));
					}
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		in.close();
		return result;
	}
}
